<template>
  <div class="chat-container">
    <div v-if="messages.length === 0" class="welcome-message">我是水质AI助手,请问有什么可以帮您?</div>
    <div v-else v-for="(message, index) in messages" :key="index" :class="message.role + '-message'">
      <div v-if="message.role === 'user'" class="user-message right">{{ message.createTime }} 你：{{ message.content }}
      </div>
      <div v-else class="bot-message">{{ message.createTime }} AI助手： {{ message.content }}</div>
    </div>
    <div class="input-container">
      <input type="text" v-model="userInput" @keyup.enter="sendMessage" placeholder="输入你的问题...">
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>


<script>
import {
  getAiDetailById,
  addAi,
} from "@/api/ai";

export default {
  data() {
    return {
      userInput: '',
      messages: [],
      message: {},
      id : undefined,
    };

  },
  computed: {

  },
  created() {
    if(this.$route.params){
      if (this.$route.params.id) {
      getAiDetailById(this.$route.params.id).then(res => {
        this.messages = res.details;
      });
      this.id = this.$route.params.id;
    }
    }
    
  },
  mounted() {

  },
  methods: {
    sendMessage() {
      if (this.userInput.trim() !== '') {
        this.messages.push({ content: this.userInput, role: 'user' });
        this.botResponse(this.userInput);
        this.userInput = '';
      }
    },
    botResponse(userInput) {
      // Simple logic for bot response, you can replace it with your AI model integration
      this.message.content = userInput;
      console.log("id is " + this.id);
      if (this.id) {
        this.message.id = this.id;
      }
      addAi(this.message).then(res => {
        console.log(res);
        this.messages.push(res);
        if (this.id) {
          return;
        };
        this.id = res.questionId;
        console.log("questionId is " + res.questionId);
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  height: 100%;
}

.welcome-message {
  //display: flex;
  padding: 20px;
  margin-top: 300px;
  text-align: center;
  font-size: x-large;
}

.user-message {
  background-color: #007bff;
  color: white;
  padding: 10px;
  border-radius: 5px;
  max-width: 100%;
}

.bot-message {
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 5px;
  max-width: 100%;
}

.right {
  margin-left: auto;
  text-align: right;
}

.input-container {
  display: flex;
  margin-top: auto;
}

input[type="text"] {
  flex: 1;
  padding: 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
}

button {
  padding: 10px 20px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}

button:hover {
  background-color: #0056b3;
}
</style>